<?php
/**
 * 云购
 * ============================================================================
 * * 版权所有 2014-2016 厦门紫竹数码科技有限公司，并保留所有权利。
 * 网站地址: http://www.lnest.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 *
 */

class yunbuy extends Lowxp{
    function __construct(){
        parent::__construct();

        #按钮
        $this->btnMenu = array(
            0=>array('url'=>'#!yunbuy/index','name'=>"".$this->L['unit_yun']."管理"),
            4=>array('url'=>"#!yunbuy/edit?com=xshow|添加".$this->L['unit_yun']."",'name'=>"添加".$this->L['unit_yun'].""),
        );

        if(YUN_GO){
            $this->btnMenu[5] = array('url'=>"#!yunbuy/edit/gobuy?com=xshow|添加".$this->L['unit_go_buy']."商品",'name'=>"添加".$this->L['unit_go_buy']."商品");
        }

        //按钮菜单
        $this->smarty->assign('btnMenu',isset($this->btnMenu)?$this->btnMenu:array());
        $this->smarty->assign('btnNo',0);

        #加载
        $this->load->model('yunbuy');
    }

    function index($page=1){
        #检索
        $_GET['status'] = isset($_GET['status']) ? $_GET['status'] : 1;
        $conds = $this->getConds();
        $condition = " WHERE buy_id<>0 ";

        $condition .= count($conds) ? ' AND '.implode(' AND ',$conds) : '';
        $orderby = " ORDER BY listorders DESC,buy_id DESC ";

        if($_GET['limit']==1){
            $condition .= " AND buynum <> 0 ";
        }
        if(!empty($_GET['price'])){
            $condition .= " AND price = '".intval($_GET['price'])."' ";
        }

        #分页
        $this->load->model('page');
        $_GET['page'] = intval($page);
        $this->page->set_vars(array('per'=>(int)$this->common['page_listrows']));

        #数据集
        $sql = "SELECT y.*,b.bus_name FROM ". $this->yunbuy->baseTable . " as y
                left join ###_business as b on b.mid=y.mid " . $condition . $orderby;
        $data['list'] = $this->page->hashQuery($sql)->result_array();

        //获取商家信息
        $this->load->model('business');
        $this->smarty->assign('business_power', $this->business->business_power);

        foreach($data['list'] as $k=>$v){
            $v['status'] = $this->yunbuy->status($v);
            $v['true_price'] = $this->db->getstr("SELECT price FROM ###_goods WHERE id = $v[goods_id]");

            //计算平台分润
            if($v['mid']){
                if(!(int) $v['bus_money']){
                    $v['bus_money_manage'] = $this->business->bus_rebate($v['goods_price'],1);
                }else{
                    $v['bus_money_manage'] = $v['goods_price'] - $v['bus_money'];
                }
            }

            $data['list'][$k] = $v;
        }

        $this->smarty->assign('data',$data);
        $this->smarty->display('manage/yunbuy/list.html');
    }

    //创建/更新
    function edit($type=''){
        //提交
        if(isset($_POST['Submit'])){
            if($_POST['post']['start_time']) $_POST['post']['start_time'] = strtotime($_POST['post']['start_time']);
            $res = $this->yunbuy->save();
            if(isset($res['code']) && $res['code']==0){
                $this->tip($res['message'],array('inIframe'=>true));
                $this->exeJs("parent.com.xhide();parent.main.refresh()");
            }else{
                $this->tip($res['message'],array('inIframe'=>true,'type'=>1));
            }
            exit;
        }

        $id = (int) $_GET['id'];
        $row = array();

        //编辑
        if($id){
            $row = $this->db->get("SELECT * FROM ". $this->yunbuy->baseTable ." WHERE buy_id=".$id);
            $ext_info = unserialize($row['ext_info']);
            if(!empty($ext_info)) $row = array_merge($row, $ext_info);
            $this->smarty->assign('id',$id);
            if($row['gobuy']==1){
                $type = 'gobuy';
            }
        }else{
            $row = array(
                'is_show'     => 1,
                'type'     => 1,
                'posid'      => 0,
            );
        }

        #商品分类
        $this->load->model('goodscat');
        $select_categorys = $this->goodscat->category_option();
        $this->smarty->assign('select_categorys', $select_categorys);

        #云购分类
        $this->load->model('yuncat');
        $select_yuncategorys = $this->yuncat->category_option($row['cid']);
        $this->smarty->assign('select_yuncategorys', $select_yuncategorys);

        if(!$id) $this->smarty->assign('btnNo',1);
        $this->smarty->assign('row',$row);
        if($type == 'gobuy'){
            $this->smarty->display('manage/yunbuy/edit_gobuy.html');
        }else{
            $this->smarty->display('manage/yunbuy/edit.html');
        }
    }

    //删除
    function del(){
        $id = (int) $_POST['id'];
        if(!$id) die;

        admin_log('删除一元购商品：'.$this->db->getstr("SELECT title FROM ".$this->yunbuy->baseTable." WHERE buy_id=".$id));
        $this->db->delete($this->yunbuy->baseTable, array('buy_id'=>$id));
        $this->yunbuy->cacheYunInfo($id,4);
        $this->tip('删除成功',array('type'=>1));
    }
	
	//下架
    function off(){
    	$id = (int) $_POST['id'];
    	if(!$id) die;
    	$row = $this->db->get("SELECT is_off FROM ###_yunbuy WHERE buy_id = '$id' AND gobuy!=1 AND member_id > 0");
    	if($row['is_off']==1)die;
    	
    	admin_log('下架一元购商品：'.$this->db->getstr("SELECT title FROM ".$this->yunbuy->baseTable." WHERE buy_id=".$id));
        $set = array('is_off'=>1,'is_show'=>0);
    	$this->db->update($this->yunbuy->baseTable,$set, array('buy_id'=>$id));
    	//下架操作需要把余额都退还给玩家
    	//第一步查询db记录中的order_id
    	$sql = "SELECT * FROM ###_yundb WHERE status=2 AND buy_id = '$id'";
    	$db_array = $this->db->select($sql);
    	if(!empty($db_array)){
	    	/*foreach($db_array as $k=>$v){
	    		if($k==0)$orderids = $v['order_id'];
	    		else $orderids .= ",".$v['order_id'];
	    	}
	    	$sql = "SELECT mid,pay_points,total,status FROM ###_yunorder WHERE order_id in ($orderids)";
	    	$order_array = $this->db->select($sql);
	    	if(!empty($order_array)){*/
	    		$this->load->model('member');
	    		foreach($db_array as $v){
	    			//if($v['status']==2){
	    				$log_arr['mid'] = $v['mid'];
	    				if($v['type']==2){
	    					$log_arr['pay_points'] = $v['total'];
	    				}elseif($v['type']==1){
	    					$log_arr['user_money'] = $v['total'];
	    				}
	    				$log_arr['desc'] = "商品下架，以余额形式退回支付金额";
	    				$this->member->accountlog(ACT_OFFSHELF,$log_arr);
	    			//}
	    		}
	    	//}
    	}
    	$this->tip('下架成功',array('type'=>1));
    }

    //订单
    function order($page=1){
        $condition = " WHERE d.id<>0 ";
        if($_GET['status']) $condition .= " AND d.status = '".intval($_GET['status'])."'";
        if($_GET['type']) $condition .= " AND d.type = '".intval($_GET['type'])."'";
        if($_GET['k']=='order_sn' && $_GET['q']){
        	$condition .= " AND o.".trim($_GET['k'])." LIKE '%".trim($_GET['q'])."%'";
        }elseif($_GET['q']){
        	if($_GET['k']=='username'){
        		$condition .= " AND d.".trim($_GET['k'])." = '".trim($_GET['q'])."'";
        	}else{
        		$condition .= " AND d.".trim($_GET['k'])." LIKE '%".trim($_GET['q'])."%'";
        	}
        }
        if($_GET['is_award']) $condition .= $_GET['is_award']==1 ? " AND d.is_award = '1'" : " AND d.is_award = '0'";
        if($_GET['start_time']) $condition .= " AND d.add_time >= '".strtotime($_GET['start_time'])."'";
        if($_GET['end_time']) $condition .= " AND d.add_time <= '".(strtotime($_GET['end_time'])+3600*24)."'";
        $this->smarty->assign($_GET);

        $orderby = " ORDER BY id DESC ";

        #分页
        $this->load->model('page');
        $_GET['page'] = intval($page);
        $this->page->set_vars(array('per'=>(int)$this->common['page_listrows']));

        #数据集
        $sql = "SELECT d.* FROM ###_yundb AS d
                LEFT JOIN ###_yunorder AS o ON o.order_id = d.order_id " . $condition . $orderby;
        $data['list'] = $this->page->hashQuery($sql)->result_array();
        if($data['list']){
            foreach($data['list'] as $k=>$v){
                $v = $this->yunbuy->getThumb($v,1);
                $data['list'][$k] = $v;
            }
        }
        $this->smarty->assign('data',$data);
        $this->smarty->display('manage/yunbuy/order.html');
    }

    //订单详情
    function detail(){
        $id = intval($_GET['id']);
        $row = $this->db->get("SELECT * FROM ###_yundb WHERE id = '$id'");
        $row['yun_code'] = explode(",",$row['yun_code']);
        #商品图片
        if($row['cover']){
            $picdata = array('id'=>$row['cover']);
            $this->load->model('upload');
            $row['cover'] = $this->upload->getGalleryImgUrls($picdata,array('thumb'));
        }
        $this->smarty->assign('row',$row);
        $this->smarty->display('manage/yunbuy/detail.html');
    }

    /** 获取过滤条件
     * @return array
     */
    function getConds(){
        $where = array();

        #关键词搜索
        $array = array('k','q');
        foreach($array as $v){
            if(!isset($_GET[$v]))$_GET[$v] = '';
        }
        if(!empty($_GET['q'])){
            $where[] = "".trim($_GET['k'])." LIKE '%".addslashes($_GET['q'])."%'";
        }

        $array = array('status','type','posid');
        foreach($array as $v){
            if(!isset($_GET[$v]))$_GET[$v] = '';
        }
        if($_GET['type']!=''){
            if($_GET['type']==3){
                $where[] = " `gobuy`=1";
            }else{
                $where[] = " `type`=".intval($_GET['type']);
            }
        }
        if($_GET['status']!=='' && $_GET['type']!=3){
            $status_sql = $this->yunbuy->status_sql($_GET['status']);
            if($status_sql){
                $status_arr = explode('AND ',$status_sql);
                foreach($status_arr as $v){
                    if(trim($v)) $where[] = $v;
                }
            }
        }
        if($_GET['posid']){
            if($_GET['posid']==1){ $where[] = " posid=1"; }
            else{ $where[] = " posid!=1"; }
        }
        if(!empty($_REQUEST['publish']) && is_numeric($_REQUEST['publish'])){
            if($_REQUEST['publish'] == 1){
                $where[] = "y.mid<1";
            }elseif($_REQUEST['publish'] == 2){
                $where[] = "y.mid>0";
            }
        }

        $this->smarty->assign($_GET);
        return $where;
    }
}